<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title :titleName="titleName">
        <template slot="btn">
          <el-button class="filter-item" plain="" size="mini" @click="handleBack">返回
          </el-button>
          <el-button class="filter-item" type="primary" size="mini" @click="handleSave">保存
          </el-button>
          <!-- <el-button class="filter-item" type="primary" icon="el-icon-check" size="mini"
            @click="handleSubmit">
            <span v-if="$route.query.type != 2">提交审批</span>
            <span v-else>提交变更审批</span>
          </el-button> -->
          <el-button class="filter-item" type="primary" size="mini" @click="handlNextStep">
            下一步
          </el-button>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">
      <!-- <div class="el-icon-warning" id="box_big">请去第三页提交审批</div> -->
      <el-form ref="ruleForm" label-position="left" :model="ruleForm" :rules="rules">

        <!--基本信息-->
        <el-row :gutter="50">
          <el-col :span="6">
            <el-form-item label="方案名称：" prop="scheme_name" label-width="95px">
              <el-input v-model="ruleForm.scheme_name" :disabled="disabled" placeholder="请输入方案名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="$route.query.id">
            <el-form-item label="流水号：" prop="scheme_no" label-width="95px">
              <el-input v-model="ruleForm.scheme_no" :disabled="disabled" placeholder="请输入方案编号"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="方案所属项目：" prop="scheme_project_id" label-width="120px">

              <el-select v-if="!disabled" v-model="ruleForm.scheme_project_id"
                         placeholder="请选择方案所属项目" style="width:100%" @change="handlProject">
                <el-option v-for="(item,index) in projectList" :key="index + 'o'"
                           :label="item.project_name" :value="item.id">
                </el-option>
              </el-select>
              <el-input v-else v-model="ruleForm.scheme_project_name" disabled/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="方案编号：" prop="scheme_code" label-width="95px">
              <el-input v-model="ruleForm.scheme_code" :disabled="disabled" placeholder="请输入方案编号"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="版本号：" prop="version_no" label-width="95px">
              <el-input v-model="ruleForm.version_no" placeholder="请输入版本号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--稳定性方案明细-->
        <item-title title="稳定性方案明细" :borderShow="false"/>

        <div class="card">
          <el-row :gutter="50">
            <!--已选方案-->
            <el-col :span="6">
              <el-card class="box-card" shadow="nerver">
                <div slot="header" class="clearfix">
                  <span>已选方案</span>
                </div>
                <div id="scrollBox">
                  <el-tree :data="conditionsInve" :props="defaultProps" default-expand-all>
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span>{{ node.label }}</span>
                      <span>
                        <el-button type="text" v-if="handlShow(node)" size="mini"
                                   @click.native.stop="() => remove(node, data)">
                          <i style="color:red" class="el-icon-delete-solid"></i>
                        </el-button>
                      </span>
                    </span>
                  </el-tree>
                </div>
              </el-card>
            </el-col>

            <!--添加样品-->
            <el-col :span="6">
              <el-card class="box-card" shadow="nerver">
                <div slot="header" class="clearfix">
                  <span>设置样品</span>
                  <!-- ruleForm.stability_scheme_type != 2 -->
                  <el-button style="float: right; padding: 3px 0" type="text" size="mini"
                             @click="hanldAdd" v-if="!booleType" class="el-icon-plus">
                    添加样品
                  </el-button>
                </div>
                <div id="scrollBox">
                  <ul class="ul">
                    <li style="display: flex;justify-content: space-between;"
                        v-for="(item,index) in sampleList" :key="item.id"
                        @click="handlSampleAdd(item)">
                      <div :class=" booleColor === item.id ? 'titleColor' : ''">{{item.sample_name}}
                      </div>
                      <div v-if="ruleForm.stability_scheme_type != 2">
                        <el-button type="text" icon="el-icon-edit" size="mini"
                                   @click.native.stop="handleEdit(index)">
                        </el-button>
                        <el-button style="color:red" type="text" icon="el-icon-delete-solid"
                                   v-if="($route.query.type == 2 && sampleList.length > 1) || $route.query.type == 1"
                                   size="mini" @click.native.stop="handleDelete(index)">
                        </el-button>
                      </div>
                    </li>
                  </ul>
                </div>
              </el-card>
            </el-col>

            <!--设置考察类型-->
            <el-col :span="6">
              <el-card class="box-card" shadow="nerver">
                <div slot="header" class="clearfix">
                  <span>设置考察类型</span>
                </div>
                <div id="scrollBox">
                  <inspection ref="inspection" @handlSucess="handlSucess" :booleColor="booleColor"
                              :conditions-inve="conditionsInve" :stability="booleType"/>
                </div>
              </el-card>
            </el-col>

            <!--设置放置条件-->
            <el-col :span="6">
              <el-card class="box-card" shadow="nerver">
                <div slot="header" class="clearfix">
                  <span>设置放置条件</span>
                </div>
                <div id="scrollBox">
                  <conditions ref="conditions" :aa="aa" :conditions-inve="conditionsInve"
                              :tabs-index="tabsIndex" :stability="booleType"/>
                </div>
              </el-card>
            </el-col>

          </el-row>
        </div>

        <!--稳定性仪器信息-->
        <!--        <item-title title="稳定性仪器信息" :borderShow="false" />-->
        <!--        <el-row :gutter="10">-->
        <!--          <template v-if="!booleType">-->
        <!--            <el-col :span="6">-->
        <!--              <el-form-item>-->
        <!--                <el-select v-model="ruleForm.instrument" filterable-->
        <!--                  clearable placeholder="仪器编号,仪器名称搜索"  @change="handlInstrument" style="width:100%">-->
        <!--                  <el-option v-for="item in options" :key="item.instrument_id"-->
        <!--                    :label="`${item.instrument_name }&#45;&#45;&#45;&#45;${item.instrument_no}`"-->
        <!--                    :value="item.instrument_id" />-->
        <!--                </el-select>-->
        <!--              </el-form-item>-->
        <!--            </el-col>-->

        <!--            <el-col :span="6">-->
        <!--              <el-form-item>-->
        <!--                <el-button class="filter-item" type="primary" :disabled="!ruleForm.instrument"-->
        <!--                  size="mini" @click="handleAddList">添加到列表-->
        <!--                </el-button>-->
        <!--              </el-form-item>-->
        <!--            </el-col>-->
        <!--          </template>-->

        <!--          <el-col :span="24">-->
        <!--            <el-form :model="formTable" :rules="formRules" class="demo-ruleForm">-->
        <!--              <el-table :data="formTable.tableData" class="table1" border style="width: 100%">-->
        <!--                <el-table-column prop="instrument_no" label="编号" align="center" />-->

        <!--                <el-table-column prop="instrument_name" label="仪器名称" align="center" />-->

        <!--                <el-table-column prop="brand_model" label="品牌类型" align="center" />-->

        <!--                <el-table-column label="参数设置" align="center">-->
        <!--                  <template slot-scope="scope">-->
        <!--                    <el-form-item v-if="!booleType" class="item_form"-->
        <!--                      :prop="'tableData.'+scope.$index + '.attrs'" :rules="formRules.attrs ">-->
        <!--                      <el-input v-model="scope.row.attrs">-->
        <!--                      </el-input>-->
        <!--                    </el-form-item>-->
        <!--                    <span v-else>{{scope.row.attrs}}</span>-->
        <!--                  </template>-->
        <!--                </el-table-column>-->

        <!--                <el-table-column label="删除" align="center" width="100" v-if="!booleType">-->
        <!--                  <template #default="{row}">-->
        <!--                    <el-button type="text" style="color:red"-->
        <!--                      @click="handlInDelete(row.instrument_id)">删除</el-button>-->
        <!--                  </template>-->
        <!--                </el-table-column>-->

        <!--              </el-table>-->
        <!--            </el-form>-->
        <!--          </el-col>-->
        <!--        </el-row>-->

      </el-form>

      <div style="text-align: center;margin-top:20px">
        <el-button class="filter-item" type="primary" size="mini" @click="handlNextStep">
          下一步,设置检验项目信息
        </el-button>
      </div>
    </div>

    <!--对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
               :before-close="cancel" :close-on-click-modal="false" v-if="open">
      <el-form ref="formOpen" :model="formOpen" :rules="openRules" size="small">
        <el-form-item label="样品名称" prop="sample_name" label-width="95px">
          <el-input v-model.trim="formOpen.sample_name" placeholder="请输入样品名称"/>
        </el-form-item>

        <el-form-item label="样品类型" prop="sample_type_info.same_type_id" label-width="95px">
          <el-select v-model="formOpen.sample_type_info.same_type_id" placeholder="请选择样品类型"
                     style="width:100%" @change="handlSampleType">
            <el-option v-for="(item,index) in sampleType" :key="index + 'o4'"
                       :label="item.sample_type_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-row :gutter="20" v-for="(item,index) in formOpen.batch_info" :key="index">
          <el-col :span="11">
            <!--            :rules="{ required: true, message: '请输入样品批号', trigger: 'blur'}"-->
            <el-form-item label="样品批号" :prop="'batch_info.' + index + '.sample_batch'"
                          :rules="openRules.sample_batch"
                          label-width="95px">
              <el-input v-model.trim="item.sample_batch" placeholder="请输入样品批号"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="样品批量" :prop="'batch_info.' + index + '.batch_num'"
                          :rules="{ required: true, message: '请输入样品批量', trigger: 'blur'}"
                          label-width="95px">
              <el-input v-model.number="item.batch_num" @input="handlBatch(item.batch_num,index)"
                        placeholder="请输入样品批量"/>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="display: flex;justify-content: space-between">
            <el-button type="text" class="el-icon-plus" @click="handAdd"></el-button>
            <el-button type="text" class="el-icon-delete"
                       v-if="formOpen.batch_info.length > 1"
                       @click="handEdi(index)" style="color:red"></el-button>
          </el-col>
        </el-row>


        <el-form-item label="样品规格" prop="packaging_nu" label-width="95px">
          <el-row :gutter="15">
            <el-col :span="7">
              <el-input v-model.number="formOpen.packaging_nu" @change="handlPackaging"
                        placeholder="请输入样品规格"/>
            </el-col>
            <el-col :span="5">
              <el-input v-model.trim="formOpen.packaging_nu_unit" ref="packaging_nu_unit"
                        style="width:70%"/>
              <span style="padding-left:20px">/</span>
            </el-col>
            <el-col :span="9">
              <span style="width:60%;padding-right:15px">包装单位</span>
              <el-input v-model.trim="formOpen.packaging_unit" ref="packaging_unit"
                        style="width:50%"/>
            </el-col>
            <el-col :span="2">
              <el-tooltip content="填写包装单位，可不填写前两个，如果填写前两个任意一个，三个输入框必填" placement="bottom"
                          effect="light">
                <i class="el-icon-question"></i>
              </el-tooltip>

            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="生产厂家" prop="producer" label-width="95px">
          <el-input v-model="formOpen.producer" placeholder="请输入生产厂家"/>
        </el-form-item>

        <el-form-item label="生产日期" prop="manufacture_date" label-width="95px">
          <el-date-picker v-model="formOpen.manufacture_date" type="date"
                          value-format="yyyy-MM-dd" @change="onChangeTime12"
                          style="width: 100%"
                          :picker-options="pickerOption" placeholder="选择日期"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancel">取 消
        </el-button>
        <el-button plain size="small" v-if="!openType" @click="handlSaveAdd">保存并继续添加
        </el-button>
        <el-button size="small" type="primary" @click="submitForm">
          保 存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="变更说明" :visible.sync="openChange" width="600px" append-to-body
               :before-close="cancelChange" :close-on-click-modal="false" v-if="openChange">
      <el-form :model="openChangeForm" ref="openChangeForm" label-width="100px">
        <el-form-item label="变更原因" prop="change_reason"
                      :rules="[{ required: true, message: '请填写变更原因', trigger: 'blur' }]">
          <el-input type="textarea" v-model="openChangeForm.change_reason"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancelChange">取 消
        </el-button>
        <el-button size="small" type="primary" @click="submitChange">
          确 定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    sampleDown,
    projectId,
    projectList,
    createSave,
    updateSave,
    updateChangeSave,
    stabilityEditor,
    subApproval,
    submitChange,
    instrument
  } from '@/api/stability/giveUp'
  import Logo from '@/layout/components/Sidebar/Logo'

  export default {
    components: {
      inspection: () => import('./inspection'),
      conditions: () => import('./conditions')
    },
    name: 'index',
    data() {
      let checkName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入样品名称'))
        } else {
          if (this.sampleList.length > 0) {
            let index = this.sampleList.findIndex(a => a.sample_name === value)
            if (index !== -1) {
              if (index === this.openIndex) {
                callback()
              } else {
                callback(new Error('样品名称已存在'))
              }
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      }
      let checkBach = (rule, value, callback) => {
        let field = rule.field.split('.')[1]
        let bo = false
        if (value === '') {
          callback(new Error('请输入批号'))
        } else {
          for (let i = 0; i < this.formOpen.batch_info.length; i++) {
            if (i !== Number(field)) {
              if (this.formOpen.batch_info[i].sample_batch === value) {
                bo = true
                break
              } else {
                bo = false
              }
            }
          }
          if (bo) {
            callback(new Error('批号重复'))
          } else {
            callback()
          }
        }

      }
      let checkSpeci = (rule, value, callback) => {
        let packaging_nu_unit = this.$refs.packaging_nu_unit.value
        let packaging_unit = this.$refs.packaging_unit.value
        if (value && packaging_nu_unit && packaging_unit) {
          callback()
        } else {
          if (value || packaging_nu_unit) {
            callback(new Error('请输入包装单位'))
          } else {
            if (
              (value === '' || value === null) &&
              packaging_nu_unit === '' &&
              packaging_unit === ''
            ) {
              callback(new Error('请输入包装单位'))
            } else {
              callback()
            }
          }
        }
      }
      return {
        titleName: '创建稳定性方案',
        disabled: false,
        defaultProps: {
          children: 'conditions',
          label: 'label'
        },
        projectList: [], //方案所属项目
        ruleForm: {
          sign_category_id: '',
          sign_category_name: '',
          id: '',
          scheme_name: '', //"方案名称",
          scheme_no: '', //"流水号",
          scheme_code: '',//方案编号
          scheme_project_id: '', //"方案所属项目id",
          scheme_project_name: '', // "方案所属项目名称",
          project_leader_id: '', // "项目负责人id",
          project_no: '',
          project_leader_name: '', //"项目负责人名称",
          version_no: '', //"版本号"
          stability_instrument_infos: '',
          stability_table_info: '',
          stability_plan: '',
          stability_details: [],
          sample_list: [],
          sample_id: '1'
        },
        rules: {
          scheme_name: [
            { required: true, message: '请填写方案名称', trigger: 'blur' }
          ],
          scheme_code: [
            { required: true, message: '请填写方案编号', trigger: 'blur' }
          ],
          scheme_project_id: [
            { required: true, message: '请选择方案所属项目', trigger: 'chenge' }
          ],
          version_no: [
            { required: true, message: '请填写版本号', trigger: 'blur' }
          ]
        },
        options: [],
        sampleType: [], //样品类型
        sampleList: [], //添加样品数组
        checlSamp: [],
        checkList: [],
        conditionsInve: [],
        tabsIndex: 0,
        checkListData: [
          {
            index: '8',
            list: [2332],
            children: [{ index: '8', list: [2332] }]
          }
        ],
        open: false,
        title: '',
        formOpen: {
          sample_name: '',
          sample_type_info: {
            same_type_id: '', //"样品类型id",
            same_type_name: '', //"样品类型名称",
            inspect_projects: []
          },
          batch_info: [{
            sample_batch: '',//样品批号
            batch_num: null// 批量
          }],
          packaging_nu: null,
          packaging_unit: '',
          packaging_nu_unit: '',
          sample_attrs: '',
          producer: '',
          id: 1,
          manufacture_date: null
        },
        openRules: {
          sample_name: [
            { required: true, validator: checkName, trigger: 'blur' }
          ],
          'sample_type_info.same_type_id': [
            { required: true, message: '请选择样品类型', trigger: 'change' }
          ],
          sample_batch: [
            { required: true, validator: checkBach, trigger: 'blur' }
          ],
          producer: [
            { required: true, message: '请填写生产厂家', trigger: 'blur' }
          ],
          packaging_nu: [{ required: true, validator: checkSpeci }],
          manufacture_date: [
            { required: true, message: '请选择生产日期', trigger: 'change' }
          ]
        },
        pickerOption: {
          disabledDate(time) {
            //此条为设置禁止用户选择今天之前的日期，包含今天。
            return time.getTime() >= Date.now() - 8.64e7
          }
        },
        openIndex: undefined,
        openType: false,
        formTable: {
          tableData: []
        },
        formRules: {
          attrs: [{ required: true, trigger: 'blur' }]
        },
        id: '',
        openChange: false,
        openChangeForm: {
          id: '',
          change_reason: ''
        },
        booleColor: -1,
        aa: {},
        instrumentList: {},
        booleType: false,

      }
    },
    //是计算属性，也可以理解为一个方法。
    computed: {},

    //属性是手动定义的所需监听的值
    watch: {},

    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.projectListData()
      this.sampleDownData()
      this.handlList()
      if (this.$route.query.id) {
        this.disabled = true
        this.titleName = '编辑稳定性方案'
        this.handlEditor()
      } else {
        this.disabled = false
      }
      this.handlMethod()
    },

    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },

    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      //获取编辑数据
      handlEditor() {
        stabilityEditor(this.$route.query.id).then(res => {
          if (res.code === 200) {
            this.ruleForm = res.data || []
            this.formTable.tableData = res.data.stability_instrument_infos || []
            this.sampleList = res.data.sample_list || []
            this.ruleForm.sample_list = this.sampleList || []
            this.ruleForm.sample_list.forEach(item => {
              if (item.packaging_nu == 0) {
                item.packaging_nu = null
              }
            })
            this.handlSampID()
            this.sampleList.forEach(item => {
              this.checlSamp.push(item.id)
            })
            this.conditionsInve = res.data.stability_details || []
            if (this.conditionsInve && this.conditionsInve.length > 0) {
              this.booleColor = Number(this.conditionsInve[0].name)
              this.aa = this.conditionsInve[0].conditions[0]
            }
            this.handlstatus()
          }
        })
      },

      //判断是否是方案变更
      handlstatus() {
        if (
          this.$route.query.type == 2 &&
          (this.ruleForm.stability_scheme_type == 1 ||
            this.ruleForm.stability_scheme_type == 2) &&
          this.ruleForm.stability_status == 3
        ) {
          this.booleType = true
        }
        if (
          this.$route.query.type == 1 &&
          this.ruleForm.stability_scheme_type == 2 &&
          this.ruleForm.stability_status == 1
        ) {
          this.booleType = true
        }
        if (
          this.$route.query.type == 1 &&
          this.ruleForm.stability_scheme_type == 1 &&
          this.ruleForm.stability_status == 1
        ) {
          this.booleType = false
        }
      },

      //方案所属项目
      projectListData: function() {
        projectList().then(res => {
          if (res.code === 200) {
            this.projectList = res.data.data || []
          }
        })
      },

      //方案所属项目事件
      handlProject: function(val) {
        this.projectList.forEach(item => {
          if (item.id === val) {
            this.ruleForm.scheme_project_name = item.project_name
            this.ruleForm.project_leader_id = item.project_person_in_charge_id
            this.ruleForm.project_leader_name = item.project_person_in_charge
            this.ruleForm.project_no = item.project_no
            this.ruleForm.sign_category_name = item.sign_category_name
            this.ruleForm.sign_category_id = item.sign_category_id
          }
        })
        if (val !== '') {
          this.$nextTick(() => {
            this.$refs.ruleForm.clearValidate('scheme_project_id')
          })
        }
      },

      //获取样品类型
      sampleDownData: function() {
        sampleDown().then(res => {
          if (res.code === 200) {
            this.sampleType = res.data || []
          }
        })
      },

      //样类型change事件
      async handlSampleType(val) {
        let arr = []
        await projectId(val).then(res => {
          if (res.code === 200) {
            arr = res.data || []
          }
        })
        if (arr.length > 0) {
          this.sampleType.forEach(item => {
            if (item.id === val) {
              this.formOpen.sample_type_info = {
                same_type_id: val,
                same_type_name: item.sample_type_name,
                inspect_projects: arr
              }
            }
          })
        }
      },

      //删除已选节点
      remove: function(node, data) {
        let parent = node.parent
        let children = parent.data.conditions || parent.data
        if (children == this.conditionsInve) {
          let index1 = children.findIndex(d => d.name === data.name)
          let index2 = this.sampleList.findIndex(a => a.id == data.name)
          children.splice(index1, 1)
          this.conditionsInve = children
          this.sampleList.splice(index2, 1)
          if (this.sampleList.length == 0) {
            this.booleColor = -1
          }
        }
        for (let i = 0; i < this.conditionsInve.length; i++) {
          if (children == this.conditionsInve[i].conditions) {
            let index11 = children.findIndex(d => d.name === data.name)
            let index22 = this.conditionsInve[i].list.findIndex(
              a => a == data.name
            )
            let index33 = this.conditionsInve[i].inspect_types.findIndex(
              a => a.inspect_type.id == data.name
            )
            children.splice(index11, 1)
            this.conditionsInve[i].conditions = children
            this.conditionsInve[i].list.splice(index22, 1)
            this.conditionsInve[i].inspect_types.splice(index33, 1)
            break
          }
          for (let j = 0; j < this.conditionsInve[i].conditions.length; j++) {
            if (children == this.conditionsInve[i].conditions[j].conditions) {
              let index111 = children.findIndex(d => d.name === data.name)
              let index222 = this.conditionsInve[i].conditions[j].list.findIndex(
                a => a == data.name
              )
              let index333 = this.conditionsInve[i].inspect_types.findIndex(
                a =>
                  a.inspect_type.id == this.conditionsInve[i].conditions[j].name
              )
              children.splice(index111, 1)
              this.conditionsInve[i].conditions[j].conditions = children
              this.conditionsInve[i].conditions[j].list.splice(index222, 1)
              if (index333 !== -1) {
                let index444 = this.conditionsInve[i].inspect_types[
                  index333
                  ].place_conditions_infos.findIndex(
                  a => a.place_conditions.id == data.name
                )
                this.conditionsInve[i].inspect_types[
                  index333
                  ].place_conditions_infos.splice(index444, 1)
              }
              break
            }
          }
        }
      },

      //判断节点是否存在
      handlShow: function(node) {
        // this.ruleForm.stability_scheme_type == 2
        console.log(node)
        if (this.booleType) {
          if (node.parent.childNodes.length > 1) {
            return true
          } else {
            return false
          }
        } else {
          return true
        }
      },

      //样品添加
      hanldAdd: function() {
        this.open = true
        this.title = '样品添加'
      },

      //样品弹框取消
      cancel: function() {
        this.formOpen = {
          sample_name: '',
          sample_type_info: {
            same_type_id: '', //"样品类型id",
            same_type_name: '', //"样品类型名称",
            inspect_projects: []
          },
          batch_info: [{
            sample_batch: '',//样品批号
            batch_num: null// 批量
          }],
          packaging_nu: null,
          packaging_unit: '',
          packaging_nu_unit: '',
          sample_attrs: '',
          producer: '',
          id: 1,
          manufacture_date: null
        }
        this.openIndex = undefined
        this.openType = false
        this.open = false
      },

      onChangeTime12(val) {
        if (val) {
          this.formOpen.manufacture_date = `${val} 00:00:00`
        }
      },

      //样品弹框保存继续
      handlSaveAdd: function() {
        if (
          this.formOpen.packaging_nu === '' ||
          this.formOpen.packaging_nu == null
        ) {
          this.formOpen.sample_attrs = this.formOpen.packaging_unit
        } else {
          this.formOpen.sample_attrs =
            this.formOpen.packaging_nu +
            this.formOpen.packaging_nu_unit +
            '/' +
            this.formOpen.packaging_unit
        }
        if (this.sampleList.length > 0) {
          this.formOpen.id = Number(this.ruleForm.sample_id) + 1
        }
        this.$refs.formOpen.validate(valid => {
          if (valid) {
            if (this.openType) {
              this.$set(this.sampleList, this.openIndex, this.formOpen)
            } else {
              if (this.sampleList.length > 0) {
                this.formOpen.id = Number(this.ruleForm.sample_id) + 1
              }
              this.sampleList.push(this.formOpen)
            }
            this.ruleForm.sample_list = this.sampleList
            this.handlSampID()
            this.formOpen = {
              sample_name: '',
              sample_type_info: {
                same_type_id: '', //"样品类型id",
                same_type_name: '', //"样品类型名称",
                inspect_projects: []
              },
              batch_info: [{
                sample_batch: '',//样品批号
                batch_num: null// 批量
              }],
              packaging_nu: null,
              packaging_unit: '',
              packaging_nu_unit: '',
              producer: ''
            }
            this.$nextTick(() => {
              this.$refs.formOpen.clearValidate('sample_type_info.same_type_id')
              this.$refs.formOpen.clearValidate('packaging_nu')
            })
            this.openIndex = undefined
            this.openType = false
          } else {
            return false
          }
        })
        this.handlList()
      },

      //样品规格事件
      handlPackaging(val) {
        this.formOpen.packaging_nu = Number(val)
      },

      //添加批号批量
      handAdd() {
        this.formOpen.batch_info.push({
          sample_batch: '',
          batch_num: null,
          t: new Date().getTime().toString()
        })
      },

      handEdi(index) {
        this.formOpen.batch_info.splice(index, 1)
      },

      handlBatch(val, index) {
        this.formOpen.batch_info[index].batch_num = Number(val)
      },

      //样品弹框确定
      submitForm: function() {
        if (
          this.formOpen.packaging_nu === '' ||
          this.formOpen.packaging_nu == null
        ) {
          this.formOpen.sample_attrs = this.formOpen.packaging_unit
        } else {
          this.formOpen.sample_attrs =
            this.formOpen.packaging_nu +
            this.formOpen.packaging_nu_unit +
            '/' +
            this.formOpen.packaging_unit
        }
        this.$refs.formOpen.validate(valid => {
          if (valid) {
            if (this.openType) {
              this.$set(this.sampleList, this.openIndex, this.formOpen)
              let index = this.conditionsInve.findIndex(
                a => a.name == this.sampleList[this.openIndex].id
              )
              if (index !== -1) {
                this.conditionsInve[index].label = this.sampleList[
                  this.openIndex
                  ].sample_name
                this.conditionsInve[index].stability_sample_info = this.formOpen
              }
            } else {
              if (this.sampleList.length > 0) {
                this.formOpen.id = Number(this.ruleForm.sample_id) + 1
              }
              this.sampleList.push(this.formOpen)
            }
            this.cancel()
            this.ruleForm.sample_list = this.sampleList
            this.handlSampID()
          } else {
            return false
          }
        })
        console.log(this.ruleForm.sample_list, '---------------')
        this.handlList()
      },

      //样品-------已选方案
      handlList() {
        let aaa = {}
        for (let i = 0; i < this.sampleList.length; i++) {
          aaa = {
            label: this.sampleList[i].sample_name,
            name: this.sampleList[i].id + '',
            stability_sample_info: this.sampleList[i],
            inspect_types: [],
            conditions: [],
            list: []
          }
          let index = this.conditionsInve.findIndex(a => a.name === aaa.name)
          if (index === -1) {
            this.conditionsInve.push(aaa)
          }
        }
      },

      //样品id处理
      handlSampID: function() {
        if (this.ruleForm.sample_list.length === 0) return
        let aa = this.ruleForm.sample_list
        aa.sort((a, b) => {
          return a.id - b.id
        })
        this.ruleForm.sample_id = aa[aa.length - 1].id
      },

      //样品编辑
      handleEdit: function(val) {
        this.title = '样品编辑'
        this.formOpen = { ...this.sampleList[val] }
        this.openIndex = val
        this.openType = true
        this.open = true
      },

      //样品删除
      handleDelete: function(index) {
        if (this.booleColor === this.sampleList[index].id) {
          this.booleColor = -1
        }
        this.sampleList.splice(index, 1)
        if (this.conditionsInve.length > 0) {
          this.conditionsInve.splice(index, 1)
        }
        this.ruleForm.sample_list = this.sampleList
        if (this.sampleList.length === 0) {
          this.formOpen.id = 1
        } else {
          this.formOpen.id = this.sampleList[this.sampleList.length - 1].id
        }
      },

      //设置样品点击事件
      handlSampleAdd: function(val) {
        this.booleColor = val.id
        let index = this.conditionsInve.findIndex(a => a.name == val.id)
        if (index !== -1) {
          this.tabsIndex = index
        }
      },

      //设置考察类型事件
      handlSucess: function(val) {
        this.tabsIndex = Number(val)
      },

      //保存
      handleSave: function() {
        this.ruleForm.sample_id = this.ruleForm.sample_id + ''
        this.ruleForm.stability_instrument_infos = this.formTable.tableData
        this.ruleForm.stability_details = this.conditionsInve
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            // let ssss = this.handlTree();
            // if (ssss.boole) {
            //   this.$message.error(ssss.msg);
            //   return;
            // }
            let commit = undefined,
              msg = ''
            if (this.$route.query.type == 1 || this.id !== '') {
              commit = updateSave
              msg = '保存成功'
            } else if (this.$route.query.type == 2) {
              commit = updateChangeSave
              msg = '方案变更保存成功'
            } else {
              commit = createSave
              msg = '创建保存成功'
            }
            commit(this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success(msg)
                if (res.data !== null) {
                  this.id = res.data.id
                  this.ruleForm.id = res.data.id
                  if (commit === updateChangeSave) {
                    this.$route.params.refresh = true
                    this.$router.push('/stability/giveUp')
                  }
                }
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        })
      },

      //提交审核
      handleSubmit() {
        if (this.ruleForm.sample_id) {
          this.ruleForm.sample_id = String(this.ruleForm.sample_id)
        }
        this.ruleForm.stability_instrument_infos = this.formTable.tableData
        this.ruleForm.stability_details = this.conditionsInve
        if (this.ruleForm.stability_table_info === '') {
          this.$message.error('检查项目表明细表为空')
          return
        }
        if (this.ruleForm.stability_plan === '') {
          this.$message.error('稳定性试验放样信息表为空')
          return
        }
        let aaa = JSON.parse(this.ruleForm.stability_table_info) || {}
        let bbb = JSON.parse(this.ruleForm.stability_plan) || []
        let ccc = this.handlTableCharm(aaa)
        if (!ccc) return
        let ddd = this.handlStableCharm(bbb)
        if (!ddd) return
        this.$refs.ruleForm.validate(async valid => {
          if (valid) {
            let ssss = this.handlTree()
            if (ssss.boole) {
              this.$message.error(ssss.msg)
              return
            }
            if (this.ruleForm.id === '') {
              await createSave(this.ruleForm).then(res => {
                if (res.code === 200) {
                  if (res.data !== null) {
                    ruleForm.id = res.data.id
                  }
                }
              })
            }
            if (this.ruleForm.stability_scheme_type == 2) {
              this.openChange = true
            } else {
              await updateSave(this.ruleForm).then(res => {
                if (res.code === 200) {
                  subApproval(this.ruleForm.id).then(res => {
                    if (res.code === 200) {
                      this.$message.success('提交审核成功')
                      this.$route.params.refresh = true
                      this.$router.push('/stability/giveUp')
                    } else {
                      this.$message.error(res.msg)
                    }
                  })
                } else {
                  this.$message.error(res.msg)
                }
              })
            }
          } else {
            return false
          }
        })
      },

      //返回
      handleBack: function() {
        this.$route.params.refresh = true
        this.$router.go(-1)
      },

      //验证tree
      handlTree() {
        var boole, msg
        if (this.sampleList.length === 0) {
          msg = '请添加样品'
          boole = true
          return { boole: boole, msg: msg }
        } else {
          let aaa = this.conditionsInve
          if (aaa.length === 0) {
            msg = '请勾选样品'
            boole = true
            return { boole: boole, msg: msg }
          } else {
            for (let i = 0; i < aaa.length; i++) {
              let bbb = aaa[i].conditions
              if (bbb.length === 0) {
                msg = `请勾选${aaa[i].label}的考察类型`
                boole = true
                return { boole: boole, msg: msg }
              } else {
                for (let j = 0; j < bbb.length; j++) {
                  if (bbb[j].conditions.length === 0) {
                    msg = `请勾选${bbb[j].label}的放置条件`
                    boole = true
                    return { boole: boole, msg: msg }
                  }
                }
              }
            }
          }
        }
        return { boole: false }
      },

      //下一步
      handlNextStep() {
        this.ruleForm.sample_id = String(this.ruleForm.sample_id)
        this.ruleForm.stability_instrument_infos = this.formTable.tableData
        this.ruleForm.stability_details = this.conditionsInve
        let type = this.$route.query.type || 1
        this.$refs.ruleForm.validate(async valid => {
          if (valid) {
            // let ssss = this.handlTree();
            // if (ssss.boole) {
            //   this.$message.error(ssss.msg);
            //   return;
            // }
            let a = 0
            if (this.ruleForm.id === '') {
              await createSave(this.ruleForm).then(res => {
                if (res.code === 200) {
                  if (res.data !== null) {
                    this.ruleForm.id = res.data.id
                    a = 0
                  }
                } else {
                  this.$message.error(res.msg)
                  a += 1
                }
              })
            }
            if (a >= 1) return
            let b = 0
            if (this.$route.query.type == 2) {
              await updateChangeSave(this.ruleForm).then(res => {
                if (res.code === 200) {
                  this.ruleForm.id = res.data.id
                  this.ruleForm.stability_scheme_type =
                    res.data.stability_scheme_type
                  this.ruleForm.stability_status = res.data.stability_status
                  b = 0
                  type = 1
                } else {
                  b = 1
                  this.$message.error(res.msg)
                }
              })
            }
            if (b == 1) return
            updateSave(this.ruleForm).then(res => {
              if (res.code === 200) {
                this.$router.push({
                  path: '/stability/giveUp/tableDetail',
                  query: { id: this.ruleForm.id, type: type }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        })
      },

      //变更审核取消
      cancelChange() {
        this.openChangeForm = {
          id: '',
          change_reason: ''
        }
        this.openChange = false
      },

      //变更审核提交
      submitChange() {
        this.$refs.openChangeForm.validate(valid => {
          if (valid) {
            updateChangeSave(this.ruleForm).then(res => {
              if (res.code === 200) {
                this.openChangeForm.id = res.data.id
                submitChange(this.openChangeForm).then(res => {
                  if (res.code === 200) {
                    this.$message.success('提交变更审批成功')
                    this.$route.params.refresh = true
                    this.$router.push('/stability/giveUp')
                    this.cancelChange()
                  } else {
                    this.$message.error(res.msg)
                  }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            return false
          }
        })
      },

      //效验检查项目表明细
      handlTableCharm(val) {
        let aa, bb, cc, dd
        for (let key in val) {
          let dic = {}
          aa = key.split('?')
          let index = this.ruleForm.stability_details.findIndex(
            a => a.stability_sample_info.id == aa[0]
          )
          if (index !== -1) {
            bb = this.ruleForm.stability_details[index].label
            let index1 = this.ruleForm.stability_details[
              index
              ].inspect_types.findIndex(a => a.inspect_type.id == aa[1])
            if (index1 !== -1) {
              cc = this.ruleForm.stability_details[index].inspect_types[index1]
                .inspect_type.inspect_type_name
              dd = bb + cc + '未勾选取样点'
            }
          }
          for (let i = 0; i < val[key].tableData.length; i++) {
            if (i !== val[key].tableData.length - 1) {
              let sss = val[key].tableData[i]
              let bo = false
              for (let obj in sss) {
                if (obj !== 'name' && obj !== 'num' && obj !== 'boole') {
                  if (typeof sss[obj] != 'string') {
                    if (!dic[obj] && typeof dic[obj] != 'bool') {
                      dic[obj] = false
                    }
                    if (sss[obj]) {
                      bo = true
                      dic[obj] = true
                      continue
                    }
                  }
                }
              }
              if (!bo) {
                this.$message.error(dd)
                return false
              }
            }
          }
          for (let a in dic) {
            if (!dic[a]) {
              this.$message.error(dd)
              return false
            }
          }
        }
        return true
      },

      //效验稳定性试验放样信息
      handlStableCharm(val) {
        for (let i = 0; i < val.length; i++) {
          let obj = val[i]
          for (let key in obj) {
            if (key.indexOf('使用倍数') != -1) {
              let sss = key.split('-')
              if (sss.length > 1 && obj[sss[1]] !== 0) {
                if (obj[key] == 0 || obj[key] == undefined) {
                  this.$message.error('样品统计使用倍数不能为0')
                  return false
                }
              }
            }
          }
        }
        return true
      },

      //稳定性仪器
      async handlMethod() {
        let data = {
          subTypes: [],
          key: ''
        }
        let res = await instrument(data)
        if (res.code === 200) {
          this.options = res.data || []
        }
      },

      //稳定仪器事件
      handlInstrument(val) {
        let index = this.options.findIndex(a => a.instrument_id === val)
        if (index !== -1) {
          this.instrumentList = this.options[index]
        }
      },

      //添加到列表
      handleAddList: function() {
        if (this.instrumentList.instrument_id === undefined) return
        if (this.instrumentList) {
          let index = this.formTable.tableData.findIndex(
            a => a.instrument_id == this.instrumentList.instrument_id
          )
          if (index == -1) {
            this.formTable.tableData.push({
              instrument_id: this.instrumentList.instrument_id, //仪器id",
              instrument_name: this.instrumentList.instrument_name, //仪器名称",
              instrument_no: this.instrumentList.instrument_no, //仪器编号",
              brand_model: this.instrumentList.brand_model, //品牌型号",
              attrs: '', //参数设置",
              locker_id: this.instrumentList.locker_id, //保管员id",
              locker_name: this.instrumentList.locker_name //保管员名称"
            })
          }
        }
        this.ruleForm.instrument = ''
        this.handlMethod('')
      },

      //删除稳定性
      handlInDelete(id) {
        let index = this.formTable.tableData.findIndex(
          a => a.instrument_id == id
        )
        if (index !== -1) {
          this.formTable.tableData.splice(index, 1)
        }
      }
    }
  }
</script>

<style scoped>
  /* @import url(); 引入css类 */
  .el-card {
    height: 260px;
    /* height: 1000px; */
  }

  #box_big {
    height: 20px;
    width: 100%;
    line-height: 20px;
    font-size: 12px;
    color: #cccccc;
    margin-bottom: 15px;
  }

  ::v-deep .el-card__header {
    background: #f5f5f5;
    height: 42px;
    line-height: 20px;
    font-size: 16px;
    box-sizing: border-box;
  }

  ::v-deep .el-card__body {
    height: 220px;
    /* height: 900px; */
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
  }

  ::v-deep #scrollBox {
    height: 100% !important;
    flex: 1 !important;
    overflow-y: auto !important;
    color: #000;
    font-size: 16px;
  }

  ::v-deep #scrollBox::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  ::v-deep #scrollBox::-webkit-scrollbar-thumb {
    border-radius: 100px;
    background: #cccccc;
  }

  ::v-deep #scrollBox::-webkit-scrollbar-track {
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
  }

  .ul {
    margin: 0;
    padding: 0;
  }

  .ul li {
    height: 30px;
    line-height: 30px;
    padding-right: 10px;
    font-size: 12px;
  }

  .ul li:hover {
    background-color: rgb(248, 248, 248);
    cursor: pointer;
  }

  .titleColor {
    color: #409eff;
  }

  ::v-deep .el-tabs__item {
    width: 130px;
    text-align: center !important;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  ::v-deep .table1 tr td {
    padding: 0 !important;
    height: 48px !important;
    overflow: visible !important;
    line-height: 48px;
  }

  ::v-deep .table1 tr td .cell {
    height: 30px !important;
    overflow: visible !important;
    line-height: 30px;
  }

  ::v-deep .item_form {
    overflow: hidden;
  }
</style>
